/**
 * 
 */
package org.istt.web.interceptor;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.istt.domain.Group;
import org.istt.domain.Menu;
import org.istt.domain.User;
import org.istt.model.MenuTreeBean;
import org.istt.service.MenuManager;
import org.istt.service.UserManager;
import org.istt.service.impl.FileServiceManagerImpl;
import org.istt.web.MailService;
import org.istt.web.WebConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author Huy
 *
 */
public class LoginInterceptor implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6987207072180086608L;
	private UserManager userManager;
	private MenuManager menuManager;
	
	@Autowired
	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}

	@Autowired
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
	 */
	@Override
	public void destroy() {
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
	 */
	@Override
	public void init() {
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		 // Get the action context from the invocation so we can access the
	    // HttpServletRequest and HttpSession objects.
		HttpServletRequest request = ServletActionContext.getRequest();
	    // Is there a "user" object stored in the user's HttpSession?
	    Object user = request.getSession().getAttribute(WebConstants.USER_INFO);
	    if (user == null) {
	    	// Process the user's login attempt.
	    	processLoginAttempt (request);
	    } 
	    return invocation.invoke ();
	}
	
	/**
	 * Attempt to process the user's login attempt delegating the work to the 
	 * SecurityManager.
	 */
	public void processLoginAttempt (HttpServletRequest request) {
	    // Get the user printciple from the HttpRequest.
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		User user = (User)userManager.loadUsersByUsername(username).get(0);
		request.getSession().setAttribute(WebConstants.USER_INFO, user);
        
		
		List<MenuTreeBean> lstMenuTreeTmp = null;
		System.out.println("Enter build menu....");
		lstMenuTreeTmp = mergePermission((User)user);
		String outputMenu = generateMenuTree(lstMenuTreeTmp);
		request.getSession().setAttribute(WebConstants.MENU_SESSION, outputMenu);

		
	}
	
	
	
	private String generateMenuTree(List<MenuTreeBean> lstMenuTreeTmp){
		String output = "";
		if(lstMenuTreeTmp!=null){
			Iterator it = lstMenuTreeTmp.iterator();
			
			String onegate = ServletActionContext.getRequest().getContextPath();
			if(lstMenuTreeTmp.size()!=0){
				output += "stBM(1,\"tree6575\",[1,\"\",\"\",\"" + onegate + "/styles/menu/blank.gif\",0,\"left\",\"default\",\"hand\",1,0,27,-1,-1,\"solid\",8,\"#5b80cc\",\"#5b80cc\",\"\",\"repeat-y\",1,\"" + onegate + "/styles/menu/explorer1.gif\",\"" + onegate + "/styles/menu/explorer1.gif\",16,16,0,\"\",\"\",\"\",\"\",0,0,0,1,\"center\",1]);\n";
				output +=("stBS(\"p0\",[0,1]);\n");
				boolean isTheFirst = true;
				String arrName = "p0i";
				int arrIndex = 0;
				int arrMnuIndex = 1;
				try {
					while(it.hasNext()){
						
						MenuTreeBean mnu = (MenuTreeBean)it.next();
						
						String strTmp = arrName + arrIndex;
						if(isTheFirst){
							isTheFirst = false;
							output +="stIT(\""+strTmp+"\",[\"         "+mnu.getMainMenu().getName()+"                         \",\"#\",\"_self\",\"\",\"\",\"\",\"\",2,26,\"bold 9pt 'Arial'\",\"#000000\",\"none\",\"transparent\",\"" + onegate + "/styles/menu/XPbanner3.gif\",\"no-repeat\",\"bold 9pt 'Arial'\",\"#000000\",\"none\",\"transparent\",\"" + onegate + "/styles/menu/XPbanner3a.gif\",\"no-repeat\",\"bold 9pt 'Arial'\",\"#000000\",\"none\",\"transparent\",\"" + onegate + "/styles/menu/XPbanner3.gif\",\"no-repeat\",\"bold 9pt 'Arial'\",\"#000000\",\"none\",\"transparent\",\"" + onegate + "/styles/menu/XPbanner3a.gif\",\"no-repeat\",1]);\n";
							output +="stBS(\"p"+arrMnuIndex+"\",[,0],\"p"+arrIndex+"\");\n";
						}else{
							output +="stIT(\""+strTmp+"\",[\"         "+mnu.getMainMenu().getName()+"                         \"],\"p0i0\");\n";
							output +="stBS(\"p"+arrMnuIndex+"\",[],\"p1\");\n";
						}
						
						// Generate sub-menu
						if(mnu.getLstSubMenu()!=null && mnu.getLstSubMenu().size()!=0){
							for (int i = 0; i < mnu.getLstSubMenu().size(); i++) {
								Menu submenu = (Menu)mnu.getLstSubMenu().get(i);
								output +="stIT(\"p"+arrMnuIndex+"i"+i+"\",[\" "+submenu.getName()+"\",\""+ onegate + "/" + submenu.getUrl()+"\",,,,\"" + onegate + "/styles/menu/folder_drag_accept.png\",\"" + onegate + "/styles/menu/folder_drag_accept.png\",20,20,\"9pt 'Arial'\",,,,\"" + onegate + "/styles/menu/XPline.gif\",\"repeat-y\",\"9pt 'Arial'\",\"#FFFFFF\",,,\"" + onegate + "/styles/menu/XPline.gif\",\"repeat-y\",,,,,\"" + onegate + "/styles/menu/XPline.gif\",\"repeat-y\",,,\"underline\",,\"" + onegate + "/styles/menu/XPline.gif\",\"repeat-y\"],\"p0i0\");\n";
								output +=";\n";	
							}
						}else{

						}
						// End of main menu
						output +="stES();\n";
						arrMnuIndex++;
						arrIndex++;
					}
				} catch (Exception e) {
					
					e.printStackTrace();
				}
				
				output +="stES();\n";
				output +="stEM();\n";
			}
		}
		return output;
		
	}
	
	private List<MenuTreeBean> mergePermission(User acc){
		List<MenuTreeBean> lstMenu = this.menuManager.getListMenuBeans();
		
		Set<Group> lstGroup = acc.getGroups();
		Hashtable<Long, Menu> selectedMenu = new Hashtable<Long, Menu>();
		
		if(lstGroup!=null && lstGroup.size()!=0){
			Iterator<Group> itGroup = lstGroup.iterator();
			while (itGroup.hasNext()) {
				Group group = (Group) itGroup.next();
				Set<Menu> setMenu = group.getMenus();
				Iterator<Menu> itMenu = setMenu.iterator();
				while (itMenu.hasNext()) {
					Menu menu = (Menu) itMenu.next();
					selectedMenu.put(menu.getId(), menu);
				}
			}
		}
		
		if(lstMenu.size()!=0){
			ArrayList<MenuTreeBean> lstRemovedMenu = new ArrayList<MenuTreeBean>();
			
			for (int i = 0; i < lstMenu.size(); i++) {
				MenuTreeBean menuBean = lstMenu.get(i);
				
				// Check parent menu
				if(!selectedMenu.containsKey(lstMenu.get(i).getMainMenu().getId())){
					lstRemovedMenu.add(menuBean);
				}else{
					// Check child menu
					List<Menu> lstSubmenu = menuBean.getLstSubMenu();
					ArrayList<Menu> lstSelectedSubmenu = new ArrayList<Menu>();
					if(lstSubmenu!=null && lstSubmenu.size()!=0){
						for (int j = 0; j < lstSubmenu.size(); j++) {
							Menu submenu = lstSubmenu.get(j);
							if(selectedMenu.containsKey(submenu.getId())){
								lstSelectedSubmenu.add(submenu);
							}
						}
						menuBean.setLstSubMenu(lstSelectedSubmenu);
					}
				}	
			}
			if(lstRemovedMenu.size()!=0){
				for (int i = 0; i < lstRemovedMenu.size(); i++) {
					lstMenu.remove(lstRemovedMenu.get(i));
				}
			}
		}
		
		return lstMenu;
	}

}
